﻿'use strict'

var app = angular.module('BlogApp', ['ngRoute']);

app.factory('BlogService', ['$http', '$q', function ($http, $q) {
    var blogArray = [];

    var postBlog = function (blogTitle, blogContent) {
        var b = { 
            blogTitle: blogTitle,
            blogContent: blogContent
        };

        var deferred = $q.defer();

        $http({
            url: 'https://bloggerapp.firebaseio.com/.json',
            method: 'POST',
            data: b,
        }).success(function (data) {
            b.id = data;
            blogArray.push(b);
            deferred.resolve(b);
        }).error(function () {
            deferred.reject();
        });

        return deferred.promise;
    }

    var getBlog = function () {
        var deferred = $q.defer();

        $http({
            url: 'https://bloggerapp.firebaseio.com/.json',
            method: 'GET'
        }).success(function (data) {
            blogArray.length = 0;
            for (var i in data) {
                data[i].iD = i;
                blogArray.push(data[i]);
            }
            deferred.resolve(blogArray);
        }).error(function () {
            deferred.reject();
        });
        return deferred.promise;
    }

    var getContent = function (i) {       
        blogArray[i];
    }

    return {
        postBlog: postBlog,
        getBlog: getBlog,
        getContent: getContent,
    };

}]);